/**
 * Copyright (c) 2018 开源 All rights reserved.
 *
 * https://www.chengcang.com
 *
 * 版权所有，侵权必究！
 */

package com.chengcang.admin.modules.security.user;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

/**
 * 用户
 *
 * @author zhanli
 */
@Slf4j
public class SecurityUser {

    private static final String USE_TENANT = "sys:use:tenant";
    private static final String USE_TENANT_TYPE = "sys:use:tenantType";
    private static final String USE_TYPE = "sys:use:type";

    public static Subject getSubject() {
        try {
            return SecurityUtils.getSubject();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 切换用户
     * @param tenantId
     */
    public static void switchTenant(Long tenantId, Integer userType,Integer tenantType) {
        try {
            ThreadContext.put(USE_TENANT,tenantId);
            ThreadContext.put(USE_TYPE,userType);
            ThreadContext.put(USE_TENANT_TYPE,tenantType);
        }catch (Exception e){
            log.error("SecurityUser 切换用户失败");
        }
    }

    /**
     * 获取用户信息
     */
    public static UserDetail getUser() {
        Subject subject = getSubject();
        if(subject == null){
            return new UserDetail();
        }

        UserDetail user = (UserDetail)subject.getPrincipal();
        if(user == null){
            return new UserDetail();
        }

        return user;
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        return getUser().getId();
    }

    /**
     * 获取用户类型
     * @return
     */
    public static Integer getUserType() {
        Object o = ThreadContext.get(USE_TENANT);
        if(o != null && o instanceof Integer){
            return (Integer) o;
        }
        return getUser().getDefaultUserType();
    }

    /**
     * 获取部门ID
     */
    public static Long getDeptId() {
        return getUser().getDeptId();
    }

    /**
     * 租户
     */
    public static Long getTenantId() {
        Object o = ThreadContext.get(USE_TENANT);
        if(o != null && o instanceof Long){
            return (Long) o;
        }
        return getUser().getDefaultTenantId();
    }

    /**
     * 客户类型
     */
    public static Integer getTenantType() {
        Object o = ThreadContext.get(USE_TENANT_TYPE);
        if(o != null && o instanceof Integer){
            return (Integer) o;
        }
        return getUser().getDefaultTenantType();
    }
}